import * as React from 'react'
import { RouteComponentProps, withRouter } from 'react-router'
import { Modal, Menu, Icon } from 'antd'
import { IMenu, USER_INFO, UserInfo } from '../../constants'
import { storage } from '../../utils/tools'

interface IState {
	name: string
	company: string
	key: string[]
}

const menuList: IMenu[] = [
	{
		key: 'logout',
		title: 'Log Out',
		path: '/logout',
		icon: 'logout'
	}
]

class SiderBar extends React.Component<RouteComponentProps, IState> {

	constructor(props: RouteComponentProps) {
		super(props)
		this.state = {
			name: '',
			company: '',
			key: []
		}
	}

	componentDidMount() {
		this.initMenu()
	}

	initMenu = () => {
		const $PROD = false
		if (!$PROD) {
			// 只有线上环境没有
			menuList.push({
				key: 'demos',
				title: 'Demos',
				path: '/admin/demo',
				icon: 'bulb'
			})
		}

		let str = storage.get(USER_INFO)
		let userInfo: UserInfo = new UserInfo()
		if (str) {
			userInfo = JSON.parse(str)

			if (userInfo.state !== 'active') {
				menuList.unshift({
					key: 'verifySteps',
					title: 'Verification Steps',
					path: '/admin/verifySteps',
					icon: 'dashboard'
				})
			}
		}

		const { pathname } = this.props.location
		const _path = pathname.split('/').slice(0, 3).join('/')
		this.setState({
			key: [_path],
			name: userInfo.name,
			company: userInfo.name,
		})
	}

	menuClick = (path: string) => {
		if (path === '/logout') {
			Modal.confirm({
				title: 'Log Out',
				content: 'Confirm log out?',
				onOk: () => {
					// return $http.post('/cms/user/logout', {}).then(res => {}).finally(() => {
					//   storage.clear()
					//   location.href = '/'
					// })
					storage.clear()
					location.href = '/'
				}
			})
		} else {
			console.log('menuClick', path);

			this.setState({ key: [path] })
			this.props.history.push(path)
		}
	}

	render() {
		const { key, name, company } = this.state

		return (
			<div>
				<a className="logo" href="/">A Card</a>
				<div className="userInfo">
					<div className="name">{name}</div>
					<div className="company">{company}</div>
				</div>
				<Menu theme="dark" selectedKeys={key}>
					{
						menuList.map(menu => {
							return <Menu.Item key={menu.path} onClick={() => this.menuClick(menu.path)}>
								<Icon type={menu.icon} />
								{menu.title}
							</Menu.Item>
						})
					}
				</Menu>
			</div>
		)
	}
}

export default withRouter(SiderBar)